// 本文件是请求拦截文件

// 基地址
const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// const baseUrl = 'https://pcapi-xiaotuxian-front.itheima.net'

// 获取token
import { useMemberStore } from '@/stores'

const requestInterceptor = {
  // options就是从uni.request传进来的参数
  invoke(options: UniNamespace.RequestOptions) {
    // 地址拼接
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url
    }
    // 超时时间
    options.timeout = 20000
    // 请求头
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    // 判断是否有token，有的话加入请求头
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}
// uniapp请求拦截
uni.addInterceptor('request', requestInterceptor)
// uniapp文件上传拦截
uni.addInterceptor('uploadFile', requestInterceptor)

type Data<T> = {
  code: number
  msg: string
  result: T
}
export const request = <T>(options: UniNamespace.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 有响应就会走这个回调(401,通用错误)
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' }).then(() => {})
          uni.showToast({ title: '登录过期，请重新登录', icon: 'none' }).then(() => {})
          reject(res)
        } else {
          uni
            .showToast({ title: (res.data as Data<T>).msg || '请求失败', icon: 'none' })
            .then(() => {})
          reject(res)
        }
      },
      fail(err) {
        uni.showToast({ title: '网络错误', icon: 'none' }).then(() => {})
        reject(err)
      },
    })
  })
}
